<template>
  <div class="exercise-question-list">
    <div class="list-header">
      <h3 class="section-title">题目列表</h3>
      <div class="list-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索题目"
          prefix-icon="Search"
          clearable
          class="search-input"
        />
        <el-select v-model="filterType" placeholder="题型" clearable class="filter-select">
          <el-option label="全部题型" value="" />
          <el-option label="单选题" value="single_choice" />
          <el-option label="多选题" value="multiple_choice" />
          <el-option label="填空题" value="fill_blank" />
          <el-option label="判断题" value="true_false" />
        </el-select>
        <el-select v-model="sortBy" placeholder="排序" class="sort-select">
          <el-option label="默认排序" value="default" />
          <el-option label="难度升序" value="difficulty_asc" />
          <el-option label="难度降序" value="difficulty_desc" />
          <el-option label="最近添加" value="created_desc" />
        </el-select>
      </div>
    </div>

    <div class="list-content">
      <el-empty v-if="filteredQuestions.length === 0" description="没有找到匹配的题目" />
      
      <el-table
        v-else
        :data="filteredQuestions"
        style="width: 100%"
        :row-class-name="getRowClass"
        @row-click="handleRowClick"
      >
        <el-table-column width="60">
          <template #default="{ row, $index }">
            <div class="question-index">{{ $index + 1 }}</div>
          </template>
        </el-table-column>
        
        <el-table-column prop="title" label="题目" min-width="250">
          <template #default="{ row }">
            <div class="question-title-cell">
              <div class="question-type-tag">
                <el-tag size="small" :type="getQuestionTypeTag(row.type).type">
                  {{ getQuestionTypeTag(row.type).label }}
                </el-tag>
              </div>
              <div class="question-title-text">{{ row.title }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="难度" width="120" align="center">
          <template #default="{ row }">
            <el-rate
              v-model="row.difficulty"
              disabled
              text-color="#ff9900"
              :max="3"
              :colors="difficultyColors"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag
              v-if="getQuestionStatus(row.id)"
              :type="getQuestionStatus(row.id).isCorrect ? 'success' : 'danger'"
              size="small"
            >
              {{ getQuestionStatus(row.id).isCorrect ? '已答对' : '已答错' }}
            </el-tag>
            <el-tag v-else type="info" size="small">未作答</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column width="80" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              plain
              @click.stop="handlePreview(row)"
            >
              预览
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <el-dialog
      v-model="previewDialogVisible"
      title="题目预览"
      width="50%"
      destroy-on-close
    >
      <div v-if="previewQuestion" class="question-preview">
        <div class="preview-header">
          <el-tag size="small" :type="getQuestionTypeTag(previewQuestion.type).type">
            {{ getQuestionTypeTag(previewQuestion.type).label }}
          </el-tag>
          <el-rate
            v-model="previewQuestion.difficulty"
            disabled
            text-color="#ff9900"
            :max="3"
            :colors="difficultyColors"
          />
        </div>
        
        <h3 class="preview-title">{{ previewQuestion.title }}</h3>
        <div class="preview-description" v-html="previewQuestion.description"></div>
        
        <!-- 单选题 -->
        <div v-if="previewQuestion.type === 'single_choice'" class="preview-options">
          <div
            v-for="option in previewQuestion.options"
            :key="option.id"
            class="preview-option"
            :class="{ 'correct-option': option.id === previewQuestion.correct_answer }"
          >
            <div class="option-marker">
              <el-icon v-if="option.id === previewQuestion.correct_answer"><Check /></el-icon>
            </div>
            <div class="option-text">{{ option.text }}</div>
          </div>
        </div>
        
        <!-- 多选题 -->
        <div v-else-if="previewQuestion.type === 'multiple_choice'" class="preview-options">
          <div
            v-for="option in previewQuestion.options"
            :key="option.id"
            class="preview-option"
            :class="{ 'correct-option': previewQuestion.correct_answer.includes(option.id) }"
          >
            <div class="option-marker">
              <el-icon v-if="previewQuestion.correct_answer.includes(option.id)"><Check /></el-icon>
            </div>
            <div class="option-text">{{ option.text }}</div>
          </div>
        </div>
        
        <!-- 填空题 -->
        <div v-else-if="previewQuestion.type === 'fill_blank'" class="preview-answer">
          <div class="answer-label">正确答案：</div>
          <div class="answer-text">{{ previewQuestion.correct_answer }}</div>
        </div>
        
        <!-- 判断题 -->
        <div v-else-if="previewQuestion.type === 'true_false'" class="preview-answer">
          <div class="answer-label">正确答案：</div>
          <div class="answer-text">{{ previewQuestion.correct_answer ? '正确' : '错误' }}</div>
        </div>
        
        <div v-if="previewQuestion.explanation" class="preview-explanation">
          <div class="explanation-label">解析：</div>
          <div class="explanation-text" v-html="previewQuestion.explanation"></div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button
            type="primary"
            @click="handleStartFromQuestion"
          >
            从此题开始练习
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { Search, Check } from '@element-plus/icons-vue'

export default {
  name: 'ExerciseQuestionList',
  components: {
    Search,
    Check
  },
  props: {
    questions: {
      type: Array,
      required: true
    },
    progress: {
      type: Object,
      default: null
    },
    selectedQuestionId: {
      type: [String, Number],
      default: null
    }
  },
  emits: ['select-question', 'start-practice'],
  setup(props, { emit }) {
    const searchQuery = ref('')
    const filterType = ref('')
    const sortBy = ref('default')
    const previewDialogVisible = ref(false)
    const previewQuestion = ref(null)
    
    const difficultyColors = ['#99A9BF', '#F7BA2A', '#FF9900']
    
    const filteredQuestions = computed(() => {
      let result = [...props.questions]
      
      // 搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(q => 
          q.title.toLowerCase().includes(query) || 
          (q.description && q.description.toLowerCase().includes(query))
        )
      }
      
      // 题型过滤
      if (filterType.value) {
        result = result.filter(q => q.type === filterType.value)
      }
      
      // 排序
      switch (sortBy.value) {
        case 'difficulty_asc':
          result.sort((a, b) => (a.difficulty || 0) - (b.difficulty || 0))
          break
        case 'difficulty_desc':
          result.sort((a, b) => (b.difficulty || 0) - (a.difficulty || 0))
          break
        case 'created_desc':
          result.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
          break
        default:
          // 默认排序，保持原顺序
          break
      }
      
      return result
    })
    
    const getQuestionTypeTag = (type) => {
      switch (type) {
        case 'single_choice':
          return { label: '单选题', type: '' }
        case 'multiple_choice':
          return { label: '多选题', type: 'success' }
        case 'fill_blank':
          return { label: '填空题', type: 'warning' }
        case 'true_false':
          return { label: '判断题', type: 'info' }
        default:
          return { label: '未知', type: 'danger' }
      }
    }
    
    const getQuestionStatus = (questionId) => {
      if (!props.progress || !props.progress.question_results) {
        return null
      }
      
      return props.progress.question_results.find(r => r.question_id === questionId) || null
    }
    
    const getRowClass = ({ row }) => {
      if (props.selectedQuestionId === row.id) {
        return 'selected-row'
      }
      return ''
    }
    
    const handleRowClick = (row) => {
      emit('select-question', row.id)
    }
    
    const handlePreview = (question) => {
      previewQuestion.value = question
      previewDialogVisible.value = true
    }
    
    const handleStartFromQuestion = () => {
      if (previewQuestion.value) {
        emit('start-practice', previewQuestion.value.id)
        previewDialogVisible.value = false
      }
    }
    
    return {
      searchQuery,
      filterType,
      sortBy,
      previewDialogVisible,
      previewQuestion,
      difficultyColors,
      filteredQuestions,
      getQuestionTypeTag,
      getQuestionStatus,
      getRowClass,
      handleRowClick,
      handlePreview,
      handleStartFromQuestion
    }
  }
}
</script>

<style scoped>
.exercise-question-list {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 10px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: var(--el-text-color-primary);
}

.list-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  width: 200px;
}

.filter-select,
.sort-select {
  width: 120px;
}

.list-content {
  flex: 1;
  overflow: auto;
}

.question-index {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: var(--el-color-info-light-9);
  color: var(--el-text-color-secondary);
  font-size: 12px;
  font-weight: 500;
}

.question-title-cell {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.question-title-text {
  flex: 1;
  word-break: break-word;
}

.selected-row {
  background-color: var(--el-color-primary-light-9) !important;
}

.question-preview {
  padding: 10px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.preview-title {
  font-size: 18px;
  margin-top: 0;
  margin-bottom: 16px;
}

.preview-description {
  margin-bottom: 20px;
  color: var(--el-text-color-primary);
}

.preview-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

.preview-option {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: var(--el-bg-color-page);
}

.correct-option {
  background-color: var(--el-color-success-light-9);
  border: 1px solid var(--el-color-success-light-5);
}

.option-marker {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 20px;
  height: 20px;
  color: var(--el-color-success);
}

.option-text {
  flex: 1;
}

.preview-answer {
  margin-bottom: 20px;
  padding: 12px;
  background-color: var(--el-color-success-light-9);
  border-radius: 4px;
}

.answer-label,
.explanation-label {
  font-weight: 500;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.preview-explanation {
  margin-top: 20px;
  padding: 12px;
  background-color: var(--el-bg-color-page);
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 